import DeviceAPI from "@/api/device";
import { type UserDeviceModel } from "@/model/user-device-model";
import { isJsonString } from "./StringUtils";

/**
 * @description 跌倒报警器工具类
 */
const DeviceAlaemFallUtils = {
  /**
   * @description 修改设备安装高度
   * @param {string} sn 设备号
   */
  async changeInstallHeight(sn: string) {
    if (!sn) {
      console.warn("sn is null");
      return;
    }

    try {
      const currentHeight = await this.getInstallHeight(sn);
      const res = await ElMessageBox.prompt("请输入安装高度(cm)", "安装高度", {
        inputValue: currentHeight,
        inputPattern: /^\+?[1-9]\d*$/,
        inputErrorMessage: "安装高度必须为正整数",
      });
      const changeHeight = res.value;
      await DeviceAPI.setFlInstallHeight(sn, changeHeight);
      ElMessage.success("修改成功");
    } catch (error) {
      console.warn(error);
    }
  },

  /**
   * @description 修改跌倒时长
   * @param {string} sn 设备号
   */
  async changeFallDuration(sn: string) {
    if (!sn) {
      console.warn("sn is null");
      return;
    }

    try {
      const currentDuration = await this.getFallDuration(sn);
      const res = await ElMessageBox.prompt("请输入跌倒时长(秒)", "跌倒时长", {
        inputValue: `${currentDuration || ""}`,
        inputPattern: /^\+?[1-9]\d*$/,
        inputErrorMessage: "跌倒时长必须为正整数",
      });
      const changeDuration = res.value;
      await DeviceAPI.setFlFallDuration(sn, changeDuration);
      ElMessage.success("修改成功");
      // TODO 请求接口修改数据
    } catch (error) {
      console.warn(error);
    }
  },

  /**
   * @description 获取安装高度
   */
  async getInstallHeight(sn: string) {
    if (!sn) {
      console.warn("sn is null");
      return;
    }
    try {
      const res: UserDeviceModel = await DeviceAPI.userDeviceDetail(sn);
      if (!isJsonString(res.ext_data || "")) return "";
      const extData = JSON.parse(res.ext_data || "");
      if (!extData.hasOwnProperty("installHeight")) return "";
      return extData.installHeight;
    } catch (error) {
      console.warn(error);
    }
  },

  /**
   * @description 获取跌倒时长数据
   * @param {string} sn 设备号
   * @returns {Promise<number>} 跌倒时长 s
   */
  async getFallDuration(sn: string) {
    if (!sn) {
      console.warn("sn is null");
      return;
    }
    try {
      try {
        const res: UserDeviceModel = await DeviceAPI.userDeviceDetail(sn);
        if (!isJsonString(res.ext_data || "")) return "";
        const extData = JSON.parse(res.ext_data || "");
        if (!extData.hasOwnProperty("fallDuration")) return "";
        return extData.fallDuration;
      } catch (error) {
        console.warn(error);
      }
    } catch (error) {
      console.warn(error);
    }
  },
};

export default DeviceAlaemFallUtils;
